package example;

import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 多环境配置管理器多例
 */
public class ConfigMultiton {
    private static final Map<String, ConfigMultiton> instances = new ConcurrentHashMap<>();
    
    private final String environment;
    private final Properties properties;
    
    private ConfigMultiton(String environment) {
        this.environment = environment;
        this.properties = new Properties();
        loadConfiguration();
    }
    
    public static synchronized ConfigMultiton getInstance(String environment) {
        return instances.computeIfAbsent(environment, ConfigMultiton::new);
    }
    
    private void loadConfiguration() {
        try {
            // 模拟加载不同环境的配置
            String configFile = "config-" + environment + ".properties";
            // properties.load(getClass().getClassLoader().getResourceAsStream(configFile));
            
            // 模拟配置内容
            properties.setProperty("database.url", "jdbc:mysql://localhost:3306/" + environment + "_db");
            properties.setProperty("cache.enabled", "true");
            properties.setProperty("log.level", environment.equals("prod") ? "ERROR" : "DEBUG");
            
            System.out.println("加载环境配置: " + environment);
        } catch (Exception e) {
            throw new RuntimeException("加载配置文件失败: " + environment, e);
        }
    }
    
    public String getProperty(String key) {
        return properties.getProperty(key);
    }
    
    public String getProperty(String key, String defaultValue) {
        return properties.getProperty(key, defaultValue);
    }
    
    public String getEnvironment() {
        return environment;
    }
    
    public static void switchEnvironment(String environment) {
        System.out.println("切换到环境: " + environment);
        // 可以在这里添加环境切换的逻辑
    }
}